package com.gviiii.baiduai.config.impl;

import com.gviiii.baiduai.config.ConfigHandler;
import com.gviiii.baiduai.config.ConfigStrategy;
import com.gviiii.baiduai.util.FileUtil;
import com.gviiii.baiduai.util.PropertiesUtil;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

import static com.gviiii.baiduai.util.PropertiesUtil.CLASSPATH_HOME;

public class FileSystemStrategy implements ConfigStrategy {

    private static final String CONFIG_DIR = "conf";

    @Override
    public Map<String,String> doOperation(String confFile) {
        if (FileUtil.exists(Paths.get(CLASSPATH_HOME, confFile))) {
            return createConfigMap(CLASSPATH_HOME, confFile);
        } else if (FileUtil.exists(Paths.get(CLASSPATH_HOME, CONFIG_DIR, confFile))) {
            return createConfigMap(Paths.get(CLASSPATH_HOME, CONFIG_DIR).toString(), confFile);
        } else if (FileUtil.exists(Paths.get(Paths.get(CLASSPATH_HOME).getParent().toString(), CONFIG_DIR, confFile))) {
            return createConfigMap(Paths.get(Paths.get(CLASSPATH_HOME).getParent().toString(), CONFIG_DIR).toString(), confFile);
        } else {
            return Collections.emptyMap();
        }
    }

    private Map<String,String> createConfigMap(String root, String confFile) {
        Properties properties = PropertiesUtil.getProperties();
        try {
            properties.load(PropertiesUtil.loadPropertiesByFileSystem(root, confFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ConfigHandler.initConfig(properties);
    }
}
